package com.yuanyi.controller;

import com.google.zxing.WriterException;
import com.yuanyi.dao.EquipmentDao;
import com.yuanyi.dao.EquipmentPicDao;
import com.yuanyi.entity.Equipment;
import com.yuanyi.entity.EquipmentPic;
import com.yuanyi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RestController
public class EquipmentController {
    @Autowired
    EquipmentDao equipmentDao;

    @Autowired
    EquipmentPicDao equipmentPicDao;

    @PostMapping("/addeq")
    @Transactional
    public Equipment addEq(@RequestBody  Equipment equipment) throws IOException, WriterException {

        Equipment eq = equipmentDao.save(equipment);
        eq.setCreatedate(new Date());

        String count = (equipmentDao.count()+1)+"";

        int diff = 10 - count.length();
        String zero = "";
        for(int i=0;i<diff;i++){
            zero +="0";
        }
        //0000000001
        eq.seteNo(zero+count);
        eq.setBarCode(StringUtil.barCode(
                StringUtil.getWechatURL("http://java59.hfbdqn.cn/baoxiu.html?eno="
                +(zero+count+""))));

        for(EquipmentPic p:eq.getEquipmentPics()){
            p.setEquipment(eq);
            equipmentPicDao.save(p);
        }
        return eq;
    }
}
